﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : CustomForm
    {
        private AppCache _appCache;
        public List<RenderTask> Tasks
        {
            get
            {
                return _appCache.Tasks;
            }
        }
        public List<RenderScheme> Schemes
        {
            get
            {
                return _appCache.Schemes;
            }
        }

        public RenderTask CurrentTask { get; set; }

        public Form1()
        {
            InitializeComponent();
            LoadCache();
            RefreshTasksGridView();
        }

        private void RefreshTasksGridView()
        {
            TasksDataGridView.Rows.Clear();
            foreach(var task in Tasks)
            {
                AddTasksGridViewRow(task);
            }
        }

        private void AddTasksGridViewRow(RenderTask renderTask)
        {
            int index = TasksDataGridView.Rows.Add();
            DataGridViewRow row = TasksDataGridView.Rows[index];

            row.Cells["TaskName"].Value = renderTask.TaskName;
            row.Cells["TaskStatus"].Value = renderTask.Status;
            TasksDataGridView.CurrentCell = row.Cells[0];
        }

        private void AddTaskButton_Click(object sender, EventArgs e)
        {
            AddTask addTask = new AddTask(this);
            addTask.Show();
        }

        public void HandleAddTask(RenderTask renderTask)
        {
            Tasks.Add(renderTask);

            AddTasksGridViewRow(renderTask);

            UpdateCurrentTask(renderTask);
        }

        private void UpdateCurrentTask(RenderTask renderTask)
        {
            CurrentTask = renderTask;
            RefreshItemPanel(renderTask);
        }

        private void RefreshItemPanel(RenderTask renderTask)
        {
            TaskItemsDataGridView.Rows.Clear();

            if (renderTask == null) return;

            foreach (RenderTaskItem item in renderTask.Items)
            {
                int index = TaskItemsDataGridView.Rows.Add();
                DataGridViewRow row = TaskItemsDataGridView.Rows[index];

                row.Cells["SourceName"].Value = item.SourceName;
                row.Cells["TargetName"].Value = item.TargetName;
                row.Cells["ItemStatus"].Value = item.Status;
            }
        }

        private void DeleteTaskButton_Click(object sender, EventArgs e)
        {
            if (TasksDataGridView.SelectedRows.Count == 0) return;

            DataGridViewRow row = TasksDataGridView.SelectedRows[0];
            int index = TasksDataGridView.Rows.IndexOf(row);
            RenderTask task = Tasks[index];

            if(task.Status == RenderTaskStatus.Running)
            {
                MessageBox.Show("当前任务正在运行不可删除！");
            }
            else
            {
                TasksDataGridView.Rows.Remove(row);
                Tasks.Remove(task);

                if(Tasks.Count > 0)
                {
                    UpdateCurrentTask(Tasks[0]);
                }
                else
                {
                    UpdateCurrentTask(null);
                }
            }
        }

        private void TasksDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;
            DataGridViewRow row = TasksDataGridView.Rows[e.RowIndex];
            string buttonText = row.Cells[e.ColumnIndex].Value.ToString();

            UpdateCurrentTask(Tasks[e.RowIndex]);
        }

        private void LookUpFile(string fileName)
        {
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.Arguments = string.Format("/c \"{0}{1}\"", "", fileName);
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = true;

            try
            {
                p.Start();
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }

        private void RunTaskButton_Click(object sender, EventArgs e)
        {
            if (CurrentTask == null) return;
            try
            {
                if (CurrentTask.Status == RenderTaskStatus.OK || CurrentTask.Status == RenderTaskStatus.Error)
                {
                    DialogResult result = MessageBox.Show("重新执行该任务吗？", "执行", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (result == DialogResult.Yes)
                    {
                        CurrentTask.Reset();
                        RefreshTaskStatus(CurrentTask);
                        CurrentTask.Run();
                        RefreshTaskStatus(CurrentTask);
                    }
                    else { return; }
                }
                else
                {
                    CurrentTask.Run();
                    RefreshTaskStatus(CurrentTask);
                }
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }
        }

        private void RefreshTaskStatus(RenderTask renderTask)
        {
            int index = Tasks.IndexOf(renderTask);
            var row = TasksDataGridView.Rows[index];
            row.Cells["TaskStatus"].Value = renderTask.Status;
            RefreshItemPanel(renderTask);
        }

        private void AddSchemeButton_Click(object sender, EventArgs e)
        {
            AddScheme addScheme = new AddScheme(this);
            addScheme.Show();
        }


        private void LoadCache()
        {
            string cacheName = "app_cache.json";
            if (File.Exists(cacheName))
            {
                string cache = File.ReadAllText("app_cache.json");
                _appCache = Newtonsoft.Json.JsonConvert.DeserializeObject<AppCache>(cache);
            }
            else
            {
                _appCache = new AppCache();
            }
        }

        private void SaveCache()
        {
            string cacheName = "app_cache.json";
            string cache = Newtonsoft.Json.JsonConvert.SerializeObject(_appCache);
            File.WriteAllText(cacheName, cache);
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            SaveCache();
        }

        private void DeleteTaskButton_Click_1(object sender, EventArgs e)
        {
            if (TasksDataGridView.SelectedRows.Count > 0)
            {
                var row = TasksDataGridView.SelectedRows[0];
                int index = TasksDataGridView.Rows.IndexOf(row);
                RenderTask scheme = Tasks[index];
                Tasks.Remove(scheme);
                TasksDataGridView.Rows.Remove(row);
            }
            UpdateCurrentTask(Tasks.FirstOrDefault());
        }

        private void LookUpSourceButton_Click(object sender, EventArgs e)
        {
            if (TaskItemsDataGridView.SelectedRows.Count == 0) return;
            DataGridViewRow row = TaskItemsDataGridView.SelectedRows[0];
            object value = row.Cells["SourceName"].Value;
            if (value == null)
            {
                MessageBox.Show("当前源文档不存在！");
            }
            else
            {
                LookUpFile(value.ToString());
            }
        }

        private void LookUpTargetButton_Click(object sender, EventArgs e)
        {
            if (TaskItemsDataGridView.SelectedRows.Count == 0) return;
            DataGridViewRow row = TaskItemsDataGridView.SelectedRows[0];
            object value = row.Cells["TargetName"].Value;
            if (value == null)
            {
                MessageBox.Show("当前源文档还没有生成目标文档！");
            }
            else
            {
                LookUpFile(value.ToString());
            }
        }
    }

    public class AppCache
    {
        public List<RenderTask> Tasks { get; set; }
        public List<RenderScheme> Schemes { get; set; }

        public AppCache()
        {
            Tasks = new List<RenderTask>();
            Schemes = new List<RenderScheme>();
        }
    }
}
